<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery\channel;

use app\common\model\delivery\CouponList;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use app\common\model\delivery\Coupon as CouponModel;
use think\annotation\route\Route;

#[Group("delivery/channel-coupon")]
class Coupon extends ChannelBase
{
    use Actions{
        add as private _add;
        edit as private _edit;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new CouponModel();
        $this->assign('couponTypeList', CouponModel::COUPONTYPE);
        $goods=array_column($this->channel->goods,'name','id');
        $this->assign('goods',$goods);
    }

    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        $where = [];
        $where[] = ['channel_id','=',$this->channel->id];
        if($this->request->post('selectpage')){
            return $this->selectpage($where);
        }
        [$where, $order, $limit, $with] = $this->buildparams($where);
        $list = $this->model
            ->withJoin($with,'left')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    #[Route('GET,POST','add')]
    public function add()
    {
        $this->parseData();
        return $this->_add();
    }

    #[Route('GET,POST','edit')]
    public function edit()
    {
        $this->parseData();
        if(!$this->request->isPost()){
            $ids=$this->request->get('ids');
            $count=CouponList::where(['coupon_id'=>$ids])->count();
            if($count>0){
                $this->error('优惠券已经发放，禁止编辑');
            }
        }
        return $this->_edit();
    }

    private function parseData()
    {
        if($this->request->isPost()){
            $this->postParams['channel_id']=$this->channel->id;
            $param=$this->request->post('row/a');
            if($param['type']=='full_minus'){
                $this->postParams['full_minus']=htmlspecialchars_decode($param['full_minus']);
            }else{
                $this->postParams['full_minus']='';
            }
        }
    }
}